<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px">
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :expand-on-click-node="false"
        node-key="deviceCode"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'deviceName',
          children: 'children',
          class: customNodeClass,
        }"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      >
        <template #default="{ data }">
          <div
            :title="data.deviceName"
            class="whitespace-nowrap overflow-ellipsis overflow-hidden"
          >
            {{ data.deviceName }}
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px">
      <Form
        :model="formTotalData"
        @register="formRegister"
        :schema="formSchema"
        :key="formKey"
      />
    </ContentWrap>
  </div>
</template>

<script setup lang="tsx">
import { ContentWrap } from "@/components/ContentWrap";
import { ref, unref, nextTick, watch, onMounted, reactive } from "vue";
import { ElTree } from "element-plus";
import { useForm } from "@/hooks/web/useForm";
import { Form, FormSchema } from "@/components/Form";
import type { DepartmentItem,DepartmentUserItem } from "@/components/DepartmentTree/types";

const props = defineProps({
  currentRow: {
    type: Object,
    default: () => undefined
  },
});

// 主表单
const { formRegister, formMethods } = useForm();
const { setValues } = formMethods;

const currentNodeKey = ref("");
const departmentList = ref([]);
// 添加formKey用于强制重新渲染表单
const formKey = ref(0);
const treeEl = ref<InstanceType<typeof ElTree> | null>(null); // 修改类型定义
const formTotalData =ref<DepartmentItem>()
const field2Value = ref("");

// 修复：确保在组件挂载后再执行相关操作
const isMounted = ref(false);

// 修改自定义节点类，只对当前选中节点应用样式
const customNodeClass = (data: any, node: any) => {
  return node.isCurrent ? "is-current-node" : "";
};

const fetchDepartment = async (id: any) => {
  if (!id) return;

  try {
    const res = await `/api/mission/deviceTree/${id}/`.get();

    res.data.map((item) => {
      item.children = [];
    });
    departmentList.value = res.data || [];
// formTotalData.value = { ...res.data[0] };
    if (res.data.length > 0) {
      currentNodeKey.value = res.data[0].deviceCode;

      // 确保组件已挂载后再设置当前节点
      if (isMounted.value && treeEl.value) {
        await nextTick();
        treeEl.value.setCurrentKey(currentNodeKey.value);

        // 触发当前节点的数据加载
        if (res.data[0]) {
          currentChange(res.data[0]);
        }
      }
    }
  } catch (error) {
    console.error("获取部门数据失败:", error);
  }
};

const currentDepartment = ref("");
watch(
  () => currentDepartment.value,
  (val) => {
    if (treeEl.value) {
      treeEl.value.filter(val);
    }
  }
);



// 修改表单 schema，确保有默认值
const formSchema = reactive<FormSchema[]>([
  {
    field: "deviceName",
    label: "设备名称（型号）",
    component: "Input",
    componentProps: {
      disabled: true,
    },
    colProps: {
      span: 24,
    },
    value: formTotalData.value?.deviceName || '' // 使用表单数据的值
  },
  {
    field: "nodeType",
    label: "节点类型",
    component: "Input",
    componentProps: {
      disabled: true,
    },
    colProps: {
      span: 24,
    },
    value: formTotalData.value?.nodeType || '' // 使用表单数据的值
  },
  {
    field: "superiorSystem",
    label: "上级系统",
    component: "Input",
     componentProps: {
      disabled: true,
    },
    colProps: {
      span: 24,
    },
    value: formTotalData.value?.superiorSystem || ''
  },
  {
    field: "superiorSubsystem",
    label: "上级分系统",
    component: "Input",
    componentProps: {
      disabled: true,
    },
    colProps: {
      span: 24,
    },
    value: formTotalData.value?.superiorSubsystem || ''
  },
  {
    field: "agreementNumber",
    label: "协议书编号",
    component: "Input",
    componentProps: {
      disabled: true,
    },
    colProps: {
      span: 24,
    },
    value: formTotalData.value?.agreementNumber || ''
  },
  {
    field: "deviceModel",
    label: "设备型号",
    component: "Input",
    componentProps: {
      disabled: true,
    },
    colProps: {
      span: 24,
    },
    value: formTotalData.value?.deviceModel || ''
  },
  {
    field: "importantLevel",
    label: "机载设备重要度类别",
    component: "Input",
    componentProps: {
      disabled: true,
    },
    colProps: {
      span: 24,
    },
    value: formTotalData.value?.importantLevel || ''
  },
  {
    field: "deviceCount",
    label: "单架安装设备数量",
    component: "Input",
    componentProps: {
      disabled: true,
    },
    colProps: {
      span: 24,
    },
    value: formTotalData.value?.deviceCount || ''
  },
  {
    field: "manufacturer",
    label: "机载设备承制单位",
    component: "Input",
    componentProps: {
      disabled: true,
    },
    colProps: {
      span: 24,
    },
    value: formTotalData.value?.manufacturer || ''
  },
  {
    field: "supervisorContact",
    label: "机载设备主管/联系电话",
    component: "Input",
    componentProps: {
      disabled: true,
    },
    colProps: {
      span: 24,
    },
    value: formTotalData.value?.supervisorContact || ''
  },
]);

// 动态表单字段



const currentChange = async (data: any) => {
  if (!data) return;

  currentNodeKey.value = data.deviceCode || data.id;
  field2Value.value = data.nodeType || "";

  // 更新表单数据
  formTotalData.value = { ...data };

  // 设置表单值
  await setFormValues(data);
};

const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};

// 修改 setFormValues 方法
const setFormValues = async (data: any) => {
  try {
    await nextTick(); // 等待下一个渲染周期

    const formData = {
      deviceName: data.deviceName || "",
      nodeType: data.nodeType || "",
      superiorSystem: data.superiorSystem || "",
      superiorSubsystem: data.superiorSubsystem || "",
      agreementNumber: data.agreementNumber || "",
      deviceModel: data.deviceModel || "",
      importantLevel: data.importantLevel || "",
      deviceCount: data.deviceCount || "",
      manufacturer: data.manufacturer || "",
      supervisorContact: data.supervisorContact || "",
      id: data.id || "",
    };

    // 设置字段值
    await setValues(formData);

    // 强制重新渲染表单
    formKey.value++;
  } catch (error) {
    console.error("设置表单值失败:", error);
  }
};

// 修复：监听 props.currentRow 的变化
watch(
  () => props.currentRow,
  (val) => {
    if (val && val.id) {
      fetchDepartment(val.id);
    }
  },
  { immediate: true, deep: true }
);

onMounted(async () => {
  isMounted.value = true;


});
</script>

<style scoped lang="less">
:deep(.el-tree-node__content) {
  height: 40px !important;
}

:deep(.is-current-node .el-tree-node .el-tree-node__content) {
  background-color: transparent !important;
  color: inherit !important;
  font-weight: normal;
}

:deep(.is-current-node > .el-tree-node__content) {
  background-color: var(--el-color-primary) !important;
  border-radius: 0 20px 20px 0;
  color: var(--el-tree-content-color) !important;
  font-weight: bold;
}

:deep(.el-tree) {
  background: transparent !important;
}
</style>
